import pandas as pd
import streamlit as st
from PIL import Image

import nf
import msds
import spec
import coa_template
import coa
import statement
import sync_records
import utils
import invoice
import sheet_update
import config

st.set_page_config(
    page_title="product-documents-management",
    #page_icon=Image.open("./data/BKD_logo.png"),
    layout="wide",    # 'wide' or 'centered'
    initial_sidebar_state="expanded",
    menu_items={
        # 'Get Help': 'robin.yu@botanikind.com',
        # 'Report a bug': "www.botanikind.com",
        'About': "# Establish by Robin 2023.07"})


if 'right_code_list' not in st.session_state:
    st.session_state.right_code_list = []

if 'batch_list' not in st.session_state:
    st.session_state.batch_list = []

if 'cliked' not in st.session_state:
    st.session_state.cliked = {'coa template': False,
                               'coa': False,
                               'spec': False,
                               'msds_eu': False,
                               'msds_us': False,
                               'msds': False,
                               'nf': False,
                               'statement': False}

@st.cache_data
def coa_template_button(i: str) -> str:
    filename = coa_template.write_coa_template(i,st.session_state.transfer_to_pdf)
    if coa_template.error_list != []:st.write(i,coa_template.error_list[0])
    return filename

@st.cache_data
def spec_button(i: str,) -> str:
    filename = spec.write_spec(i)
    if st.session_state.transfer_to_pdf:
        filename = utils.conver2pdf(filename)
    return filename

@st.cache_data
def nf_button(i: str) -> str:
    filename,remain_item = nf.write_nf(i)
    if remain_item.size>0:
        st.write(f'{i}不在清单中的营养成分：{remain_item}')
    if st.session_state.transfer_to_pdf:
        filename = utils.conver2pdf(filename)
    return filename

@st.cache_data
def msds_button(i: str, msds_type: str) -> str:
    filename = ''
    if msds_type == "msds_eu":
        _, filename, error_list = msds.write_msds(i)
        if error_list != []:
            st.write(f"缺少{error_list}")
        if st.session_state.transfer_to_pdf:
            filename = utils.conver2pdf(filename)

    elif msds_type == "msds_us":
        filename, _, error_list = msds.write_msds(i)
        if error_list != []:
            st.write(f"缺少{error_list}")
        if st.session_state.transfer_to_pdf:
            filename = utils.conver2pdf(filename)

    elif msds_type == "all":
        msds_us,msds_eu, error_list = msds.write_msds(i)
    return filename

@st.cache_data
def coa_button(batch_list:list):
    def gen_coa(batch):
        coa1 = coa.COA(batch)
        filename = ""
        if coa1.error != []:st.write(batch,coa1.error)
        if coa1.error_item != []:
            st.write(batch,coa1.error_item)
        else:
            filename = coa1.write_coa()
            if coa1.error != []:st.write(coa1.code,coa1.error[0])
            print(filename)
            if st.session_state.transfer_to_pdf:
                filename = utils.conver2pdf(filename)
        return filename,coa1.code
    return_list = []
    for batch in st.session_state.batch_list:
        filename,code = gen_coa(batch)
        return_list.append((code,batch,filename))    
    return return_list

@st.cache_data
def statement_button(i: str) -> str:
    filename =""
    statment0 = statement.Statement(i)
    filename = statment0.write_statements()
    st.write(statment0.error)
    if st.session_state.transfer_to_pdf:
        filename = utils.conver2pdf(filename)
    return filename 

def upload_button(i) -> str:
    coai = coa.COA(i)
    info=coai.upload_coa()
    st.success(info)

def clear_cache(type):
    coa_button.clear()
    coa_template_button.clear()
    spec_button.clear()
    statement_button.clear()
    msds_button.clear()
    nf_button.clear()
    st.success("All caches cleared")

func_map = {"coa":coa_button.clear,
            'coa template':coa_template_button.clear,
            "spec":spec_button.clear,
            "msds":msds_button.clear,
            'msds_eu':msds_button.clear,
            'msds_us':msds_button.clear,
            "statement":statement_button.clear,
            "nf":nf_button.clear,}


def transfer_to_pdf(abc):
    st.session_state.transfer_to_pdf = True
    
def click_button(how):
    keys = list(st.session_state.cliked.keys())
    keys.remove('coa')

    if how !='all':
        st.session_state.cliked[how] = True
        #print(how,func_map.keys())
        # 清除缓存
        if how in func_map.keys():
            return func_map[how]()
        else:
            print("!Error No such item in func_map.keys")
    else:
        for m in keys:click_button(m)

#@st.cache_data
def get_product_list():
    df_raw = pd.read_csv('./data/product_info.csv')
    df_raw = df_raw.loc[:,["Product Code","Product Name","Type","Item","Target","Method"]]
    product_list = df_raw["Product Code"].unique()
    return product_list

st.header("Product Documents Management")

with st.sidebar:
    with st.container():
        product_code = st.text_input("Please Input Product Codes or Batchs").upper()
        product_code_list = product_code.split(' ')       
        product_list = get_product_list()
        if product_code:
            st.write("You entered : ", product_code_list)
            for i in product_code_list:
                try:
                    if i in product_list:
                        st.session_state.right_code_list.append(i)
                    elif len(i)==10:
                        st.session_state.batch_list.append(i)
                    else:
                        st.write("Invalid Product Code: ", i)
                        
                except Exception as e:
                    print(e)
             # 排序，去重
            st.session_state.right_code_list = list(set(st.session_state.right_code_list))
            st.session_state.batch_list = list(set(st.session_state.batch_list))
         
            st.write("Right Code List : ",st.session_state.right_code_list)
            st.write("Batch List : ",st.session_state.batch_list)
            
            
tab1,tab4 = st.tabs(
    ["Control pannel","发票识别"])
with tab1:
    col1,col2 = st.columns(2)
    with col1:
        with st.container():
            col1_1,col1_2 = st.columns(2)
            col1_2.checkbox("Transfer to pdf",key = 'transfer_to_pdf')
            col1_1.button("Generate All",on_click=click_button,args=['all'])
            
        with st.container():
            col1_1,col1_2 = st.columns(2)
            col1_1.button("Coa template", on_click=click_button, args=["coa template"])
            if st.session_state.cliked['coa template']:
                for i in st.session_state.right_code_list:
                    filename = coa_template_button(i)
                    with open(filename, 'rb') as f:
                        col1_2.download_button(
                            f"Download {i} COA temeplate", f, file_name=filename.split("\\")[-1])
                        
        with st.container():
            col2_1,col2_2 = st.columns(2)
            col2_1.button("Specification",on_click=click_button, args=["spec"])
            if st.session_state.cliked['spec']:
                for i in st.session_state.right_code_list:
                    filename = spec_button(i)
                    with open(filename, 'rb') as f:
                        col2_2.download_button(
                            f"Download {i} spec", f, file_name=filename.split("\\")[-1])

        with st.container():
            col3_1,col3_2 = st.columns(2)
            col3_1.button("Nutrients", on_click=click_button, args=["nf"])
            if st.session_state.cliked['nf']:
                for i in st.session_state.right_code_list:
                    filename =nf_button(i)
                    with open(filename, 'rb') as f:
                        col3_2.download_button(
                            f"Download {i} Nutrients", f, file_name=filename.split("\\")[-1])
        
        with st.container():
            col4_1,col4_2 = st.columns(2)
            col4_1.button("Statement", on_click=click_button,
                        args=["statement"])
            if st.session_state.cliked['statement']:
                for i in st.session_state.right_code_list:
                    filename = statement_button(i)
                    with open(filename, 'rb') as f:
                        col4_2.download_button(
                            f"Download {i} Statement", f, file_name=filename.split("\\")[-1])         
        with st.container():
            col5_1,col5_2 = st.columns(2)               
            col5_1.button("MSDS EU", on_click=click_button, args=["msds_eu"])
            if st.session_state.cliked['msds_eu']:
                for i in st.session_state.right_code_list:
                    filename = msds_button(i, 'msds_eu')
                    with open(filename, 'rb') as f:
                        col5_2.download_button(
                            f"Download {i} MSDS EU", f, file_name=filename.split("\\")[-1])
        with st.container():
            col6_1,col6_2 = st.columns(2)    
            col6_1.button("MSDS US", on_click=click_button, args=["msds_us"])
            if st.session_state.cliked['msds_us']:
                for i in st.session_state.right_code_list:
                    filename = msds_button(i, 'msds_us')
                    with open(filename, 'rb') as f:
                        col6_2.download_button(
                            f"Download {i} MSDS US", f, file_name=filename.split("\\")[-1])
    
    with col2:
        contanier2_1 = st.container(border=True)
        contanier2_2 = st.container(border=False)
        contanier2_3 = st.container(border=False)
              
        contanier2_1.checkbox("Incremental updating",key="update_record",value=True)
        with contanier2_1:
            column1, column2 = st.columns(2)
            if column1.button("spec,nf,coa template"):
                product_info = sync_records.Spec()
                product_info.update(st.session_state.update_record)
                clear_cache(type)
                st.success("complete!")

            if column2.button("statement"):
                product_info = sync_records.Statement()
                product_info.update(st.session_state.update_record)
                clear_cache(type)
                st.success("complete!")
        contanier2_1.caption("Update documents data")      
        
        with contanier2_2:
            col2_1,col2_2,col2_3 = st.columns(3)
            if col2_1.button("coa target"):
                product_info = sync_records.Coa()
                product_info.update(st.session_state.update_record)
                clear_cache(type)
                st.success("complete!")
            if col2_2.button("test report"):
                product_info = sync_records.TestReport()
                product_info.update(st.session_state.update_record)
                clear_cache(type)
                st.success("complete!")
                
            if col2_3.button("Request"):
                sync_records.TestReport().update()
                sheet_update.update_request_coa()
                st.success("complete!")
        #contanier2_2.caption("update COA data")  
        
        with contanier2_3:
            
            st.button("COA", on_click=click_button, args=["coa"])
            if st.session_state.cliked['coa']:
                coa_list = coa_button(st.session_state.batch_list)
                for i in coa_list:
                    code,batch,filename = i
                    with open(filename,"rb") as f:
                        st.download_button(label = f"Download {code} {batch} COA",
                                            data = f, 
                                            file_name=filename.split("\\")[-1]
                                            )
                    st.button(f'Upload {code} {batch}', on_click=upload_button,args=[batch])
        

with tab4:
    uploaded_files = st.file_uploader("选择要读取的发票", accept_multiple_files=True)
    if st.button("开始识别"):
        df = invoice.read(uploaded_files)
        st.dataframe(df)
        st.success(f"识别完成! 合计 {round(df['金额'].sum(),2)} 元")
        st.download_button(
        label="Download data as CSV",
        data=df.to_csv(index=False).encode('utf-8'),
        file_name='发票统计.csv',
        mime='text/csv',
        )
